<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en">
<!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Handling failures and exceptions - The .NET Core ORM Cookbook</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="css/theme.css" type="text/css" />
    <link rel="stylesheet" href="css/theme_colors.css" type="text/css" />
    <link rel="stylesheet" href="css/styles/vs.css">
    <link rel="stylesheet" href="css/font-awesome.4.5.0.min.css">
</head>
<body role="document">
    <div class="grid-for-nav">
        <nav data-toggle="nav-shift" class="nav-side stickynav">
            <div class="side-nav-search">
                <a href="index.htm"><i class="fa fa-home"></i> The .NET Core ORM Cookbook</a>
                <div role="search">
                    <form id="search-form" class="form" action="Docnet_search.htm" method="get">
                        <input type="text" name="q" placeholder="Search docs" />
                    </form>
                </div>
            </div>
            <div class="menu menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="tocentry"><a href="index.htm">Home</a>
</li>

<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="ORMs.htm">ORMs</a></span>
</li>
<li class="tocentry"><a href="FAQ.htm">FAQ</a>
</li>
<li class="tocentry">
<ul>
<li><span class="navigationgroup"><i class="fa fa-caret-down"></i> <a href="StandardCRUDscenarios.htm">Standard CRUD scenarios</a></span></li>
<li class="tocentry"><a href="SingleModelCrud.htm">Operations on a single entity type</a>
</li>
<li class="tocentry"><a href="MultipleCrud.htm">Operations on sets</a>
</li>
<li class="tocentry"><a href="ModelWithChildren.htm">Operations on a graph of multiple entity types</a>
</li>
<li class="tocentry"><a href="Immutable.htm">Operations on immutable entities</a>
</li>
<li class="tocentry current"><a class="current" href="TryCrud.htm">Handling failures and exceptions</a>
<ul class="currentrelative">
<li class="tocentry"><a href="#scenario-prototype">Scenario Prototype</a></li>

<li class="tocentry"><a href="#ado.net">ADO.NET</a></li>

<li class="tocentry"><a href="#chain">Chain</a></li>

<li class="tocentry"><a href="#dapper">Dapper</a></li>

<li class="tocentry"><a href="#dbconnector">DbConnector</a></li>

<li class="tocentry"><a href="#entity-framework-6">Entity Framework 6</a></li>

<li class="tocentry"><a href="#entity-framework-core">Entity Framework Core</a></li>

<li class="tocentry"><a href="#linq-to-db">LINQ to DB</a></li>

<li class="tocentry"><a href="#llblgen-pro">LLBLGen Pro</a></li>

<li class="tocentry"><a href="#nhibernate">NHibernate</a></li>

<li class="tocentry"><a href="#repodb">RepoDb</a></li>

<li class="tocentry"><a href="#servicestack">ServiceStack</a></li>



</ul>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="OperationswithaForeignKeybasedLookupTable.htm">Operations with a Foreign Key based Lookup Table</a></span>
</li>

</ul>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Fetchingdatascenarios.htm">Fetching data scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Advancedscenarios.htm">Advanced scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Sortingscenarios.htm">Sorting scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Storedprocedurescenarios.htm">Stored procedure scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Auditingandhistoryscenarios.htm">Auditing and history scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Multi-Tenancyscenarios.htm">Multi-Tenancy scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="UnknownDatabasescenarios.htm">Unknown Database scenarios</a></span>
</li>
</ul>
				<div class="toc-footer">
					<span class="text-small">
						<hr/>
						<a href="https://github.com/FransBouma/DocNet" target="_blank">Made with <i class="fa fa-github"></i> DocNet</a>
					</span>
				</div>	
			</div>
            &nbsp;
        </nav>
        <section data-toggle="nav-shift" class="nav-content-wrap">
            <nav class="nav-top" role="navigation" aria-label="top navigation">
                <i data-toggle="nav-top" class="fa fa-bars"></i>
                <a href="index.htm">The .NET Core ORM Cookbook</a>
            </nav>
            <div class="nav-content">
                <div role="navigation" aria-label="breadcrumbs navigation">
                    <div class="breadcrumbs">
<ul><li><a href="index.htm">Home</a></li> / <li><a href="StandardCRUDscenarios.htm">Standard CRUD scenarios</a></li> / <li><a href="TryCrud.htm">Handling failures and exceptions</a></li></ul>
					
                    </div>
                    <hr />
                </div>
                <div role="main">
                    <div class="section">
<h1 id="tryget-tryupdate-and-trydelete-operations">TryGet, TryUpdate, and TryDelete Operations<a class="headerlink" href="#tryget-tryupdate-and-trydelete-operations" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h1>
<p>These scenarios demonstrate the difference between operations that fail silently and operations that fail with an exception.</p>
<h2 id="scenario-prototype">Scenario Prototype<a class="headerlink" href="#scenario-prototype" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public interface ITryCrudScenario&lt;TEmployeeClassification&gt;
   where TEmployeeClassification : class, IEmployeeClassification, new()
{
    /// &lt;summary&gt;
    /// Create a new EmployeeClassification row, returning the new primary key.
    /// &lt;/summary&gt;
    int Create(TEmployeeClassification classification);

    /// &lt;summary&gt;
    /// Delete a EmployeeClassification row using its primary key. If no matching row is found, an exception is thrown.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;The specific exception thrown is not defined.&lt;/remarks&gt;
    void DeleteByKeyOrException(int employeeClassificationKey);

    /// &lt;summary&gt;
    /// Delete a EmployeeClassification row using its primary key. Returns true if the row was updated, false if no matching row was found.
    /// &lt;/summary&gt;
    bool DeleteByKeyWithStatus(int employeeClassificationKey);

    /// &lt;summary&gt;
    /// Delete a EmployeeClassification row using an object. If no matching row is found, an exception is thrown.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;The specific exception thrown is not defined.&lt;/remarks&gt;
    void DeleteOrException(TEmployeeClassification classification);

    /// &lt;summary&gt;
    /// Delete a EmployeeClassification row using an object. Returns true if the row was updated, false if no matching row was found.
    /// &lt;/summary&gt;
    bool DeleteWithStatus(TEmployeeClassification classification);

    /// &lt;summary&gt;
    /// Gets an EmployeeClassification row by its name. If no row is found, an exception is thrown.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;The specific exception thrown is not defined.&lt;/remarks&gt;
    TEmployeeClassification FindByNameOrException(string employeeClassificationName);

    /// &lt;summary&gt;
    /// Gets an EmployeeClassification row by its name. Assume the name is unique. If no row is found, a null is returned.
    /// &lt;/summary&gt;
    TEmployeeClassification? FindByNameOrNull(string employeeClassificationName);

    /// &lt;summary&gt;
    /// Gets an EmployeeClassification row by its primary key. If no row is found, an exception is thrown.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;The specific exception thrown is not defined.&lt;/remarks&gt;
    TEmployeeClassification GetByKeyOrException(int employeeClassificationKey);

    /// &lt;summary&gt;
    /// Gets an EmployeeClassification row by its primary key. If no row is found, a null is returned.
    /// &lt;/summary&gt;
    TEmployeeClassification? GetByKeyOrNull(int employeeClassificationKey);

    /// &lt;summary&gt;
    /// Update a EmployeeClassification row. If no matching row is found, an exception is thrown.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;The specific exception thrown is not defined.&lt;/remarks&gt;
    void UpdateOrException(TEmployeeClassification classification);

    /// &lt;summary&gt;
    /// Update a EmployeeClassification row. Returns true if the row was updated, false if no matching row was found.
    /// &lt;/summary&gt;
    bool UpdateWithStatus(TEmployeeClassification classification);
}
</code></pre>

<h2 id="ado.net">ADO.NET<a class="headerlink" href="#ado.net" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>The trick to the <code>Update</code> and <code>Delete</code> methods is to read back the row counts from <code>ExecuteNonQuery</code>.</p>
<pre><code class="cs">public class TryCrudScenario : SqlServerScenarioBase, ITryCrudScenario&lt;EmployeeClassification&gt;
{
    public TryCrudScenario(string connectionString) : base(connectionString)
    { }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, classification.EmployeeClassificationName);
            return (int)cmd.ExecuteScalar();
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        const string sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, employeeClassificationKey);
            var rowCount = cmd.ExecuteNonQuery();
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        const string sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, employeeClassificationKey);
            return 1 == cmd.ExecuteNonQuery();
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, classification.EmployeeClassificationKey);
            var rowCount = cmd.ExecuteNonQuery();
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, classification.EmployeeClassificationKey);
            return 1 == cmd.ExecuteNonQuery();
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        const string sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @EmployeeClassificationName;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, employeeClassificationName);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    throw new DataException($&quot;No row was found for '{employeeClassificationName}'.&quot;);

                return new EmployeeClassification()
                {
                    EmployeeClassificationKey = reader.GetInt32(reader.GetOrdinal(&quot;EmployeeClassificationKey&quot;)),
                    EmployeeClassificationName = reader.GetString(reader.GetOrdinal(&quot;EmployeeClassificationName&quot;))
                };
            }
        }
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        const string sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @EmployeeClassificationName;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, employeeClassificationName);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    return null;

                return new EmployeeClassification()
                {
                    EmployeeClassificationKey = reader.GetInt32(reader.GetOrdinal(&quot;EmployeeClassificationKey&quot;)),
                    EmployeeClassificationName = reader.GetString(reader.GetOrdinal(&quot;EmployeeClassificationName&quot;))
                };
            }
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        const string sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, employeeClassificationKey);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);

                return new EmployeeClassification()
                {
                    EmployeeClassificationKey = reader.GetInt32(reader.GetOrdinal(&quot;EmployeeClassificationKey&quot;)),
                    EmployeeClassificationName = reader.GetString(reader.GetOrdinal(&quot;EmployeeClassificationName&quot;))
                };
            }
        }
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        const string sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, employeeClassificationKey);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    return null;

                return new EmployeeClassification()
                {
                    EmployeeClassificationKey = reader.GetInt32(reader.GetOrdinal(&quot;EmployeeClassificationKey&quot;)),
                    EmployeeClassificationName = reader.GetString(reader.GetOrdinal(&quot;EmployeeClassificationName&quot;))
                };
            }
        }
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, classification.EmployeeClassificationKey);
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, classification.EmployeeClassificationName);
            var rowCount = cmd.ExecuteNonQuery();
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, classification.EmployeeClassificationKey);
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, classification.EmployeeClassificationName);
            return 1 == cmd.ExecuteNonQuery();
        }
    }
}
</code></pre>

<h2 id="chain">Chain<a class="headerlink" href="#chain" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    readonly SqlServerDataSource m_DataSource;

    public TryCrudScenario(SqlServerDataSource dataSource)
    {
        m_DataSource = dataSource;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return m_DataSource.Insert(classification).ToInt32().Execute();
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        var count = m_DataSource.DeleteByKey&lt;EmployeeClassification&gt;(employeeClassificationKey).Execute();
        if (count == 0)
            throw new MissingDataException();
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        return 1 == m_DataSource.DeleteByKey&lt;EmployeeClassification&gt;(employeeClassificationKey).Execute();
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var count = m_DataSource.Delete(classification).Execute();
        if (count == 0)
            throw new MissingDataException();
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return 1 == m_DataSource.Delete(classification).Execute();
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        return m_DataSource.From&lt;EmployeeClassification&gt;(new { employeeClassificationName })
            .ToObject().Execute();
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        return m_DataSource.From&lt;EmployeeClassification&gt;(new { employeeClassificationName })
            .ToObjectOrNull().Execute();
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        return m_DataSource.GetByKey&lt;EmployeeClassification&gt;(employeeClassificationKey).ToObject().Execute();
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        return m_DataSource.GetByKey&lt;EmployeeClassification&gt;(employeeClassificationKey).ToObjectOrNull().Execute();
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        m_DataSource.Update(classification).Execute();
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return 1 == m_DataSource.Update(classification, UpdateOptions.IgnoreRowsAffected).Execute();
    }
}
</code></pre>

<h2 id="dapper">Dapper<a class="headerlink" href="#dapper" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>Like ADO.NET, this uses the row counts returned from the <code>Execute</code> command.</p>
<pre><code class="cs">public class TryCrudScenario : ScenarioBase, ITryCrudScenario&lt;EmployeeClassification&gt;
{
    public TryCrudScenario(string connectionString) : base(connectionString)
    {
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var con = OpenConnection())
            return (int)con.Insert(classification);
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        {
            var rowCount = con.Execute(sql, new { employeeClassificationKey });
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
            return 1 == con.Execute(sql, new { employeeClassificationKey });
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        {
            var rowCount = con.Execute(sql, classification);
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
            return 1 == con.Execute(sql, classification);
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        var sql = @&quot;SELECT  ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @EmployeeClassificationName;&quot;;

        using (var con = OpenConnection())
            return con.QuerySingle&lt;EmployeeClassification&gt;(sql, new { employeeClassificationName });
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        var sql = @&quot;SELECT  ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @EmployeeClassificationName;&quot;;

        using (var con = OpenConnection())
            return con.QuerySingleOrDefault&lt;EmployeeClassification&gt;(sql, new { employeeClassificationName });
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        var sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
            return con.QuerySingle&lt;EmployeeClassification&gt;(sql, new { employeeClassificationKey });
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        var sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
            return con.QuerySingleOrDefault&lt;EmployeeClassification&gt;(sql, new { employeeClassificationKey });
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        {
            var rowCount = con.Execute(sql, classification);
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
            return 1 == con.Execute(sql, classification);
    }
}
</code></pre>

<h2 id="dbconnector">DbConnector<a class="headerlink" href="#dbconnector" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>DbConnector's <code>NonQuery</code> returns the number of affected rows, if the non-query ran successfully, from the ADO.NET <code>ExecuteNonQuery</code> command.</p>
<pre><code class="cs">public class TryCrudScenario : ScenarioBase, ITryCrudScenario&lt;EmployeeClassification&gt;
{
    public TryCrudScenario(string connectionString) : base(connectionString)
    {
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return DbConnector.Scalar&lt;int&gt;(
        @&quot;INSERT INTO &quot; + EmployeeClassification.TableName
        + @&quot;(
                EmployeeClassificationName,
                IsEmployee,
                IsExempt
            ) 
            OUTPUT Inserted.EmployeeClassificationKey
            VALUES (
                @EmployeeClassificationName,
                @IsEmployee,
                @IsExempt
            )&quot;
        , classification)
        .Execute();
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @employeeClassificationKey;&quot;;

        var rowCount = DbConnector.NonQuery(sql, new { employeeClassificationKey }).Execute();
        if (rowCount != 1)
            throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @employeeClassificationKey;&quot;;

        return 1 == DbConnector.NonQuery(sql, new { employeeClassificationKey }).Execute();
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        var rowCount = DbConnector.NonQuery(sql, classification).Execute();
        if (rowCount != 1)
            throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;DELETE HR.EmployeeClassification WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        return 1 == DbConnector.NonQuery(sql, classification).Execute();
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        var sql = @&quot;SELECT  ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @employeeClassificationName;&quot;;


        return DbConnector.ReadSingle&lt;EmployeeClassification&gt;(sql, new { employeeClassificationName }).Execute();
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        var sql = @&quot;SELECT  ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationName = @employeeClassificationName;&quot;;


        return DbConnector.ReadSingleOrDefault&lt;EmployeeClassification&gt;(sql, new { employeeClassificationName }).Execute();
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        var sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @employeeClassificationKey;&quot;;


        return DbConnector.ReadSingle&lt;EmployeeClassification&gt;(sql, new { employeeClassificationKey }).Execute();
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        var sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @employeeClassificationKey;&quot;;


        return DbConnector.ReadSingleOrDefault&lt;EmployeeClassification&gt;(sql, new { employeeClassificationKey }).Execute();
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        var rowCount = DbConnector.NonQuery(sql, classification).Execute();
        if (rowCount != 1)
            throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;UPDATE HR.EmployeeClassification
                    SET EmployeeClassificationName = @EmployeeClassificationName
                    WHERE EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        return 1 == DbConnector.NonQuery(sql, classification).Execute();
    }
}
</code></pre>

<h2 id="entity-framework-6">Entity Framework 6<a class="headerlink" href="#entity-framework-6" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public TryCrudScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            context.EmployeeClassification.Add(classification);
            context.SaveChanges();
            return classification.EmployeeClassificationKey;
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassification.Find(employeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassification.Remove(temp);
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassification.Find(employeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassification.Remove(temp);
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassification.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassification.Remove(temp);
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassification.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassification.Remove(temp);
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).Single();
        }
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).SingleOrDefault();
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassification.Find(employeeClassificationKey) ?? throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassification.Find(employeeClassificationKey);
        }
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Get a fresh copy of the row from the database
            var temp = context.EmployeeClassification.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                //Copy the changed fields
                temp.EmployeeClassificationName = classification.EmployeeClassificationName;
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Get a fresh copy of the row from the database
            var temp = context.EmployeeClassification.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                //Copy the changed fields
                temp.EmployeeClassificationName = classification.EmployeeClassificationName;
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }
}
</code></pre>

<h2 id="entity-framework-core">Entity Framework Core<a class="headerlink" href="#entity-framework-core" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public TryCrudScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            context.EmployeeClassifications.Add(classification);
            context.SaveChanges();
            return classification.EmployeeClassificationKey;
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassifications.Find(employeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassifications.Remove(temp);
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassifications.Find(employeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassifications.Remove(temp);
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassifications.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassifications.Remove(temp);
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Find the row you wish to delete
            var temp = context.EmployeeClassifications.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                context.EmployeeClassifications.Remove(temp);
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassifications.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).Single();
        }
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassifications.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).SingleOrDefault();
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassifications.Find(employeeClassificationKey) ?? throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
        {
            return context.EmployeeClassifications.Find(employeeClassificationKey);
        }
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Get a fresh copy of the row from the database
            var temp = context.EmployeeClassifications.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                //Copy the changed fields
                temp.EmployeeClassificationName = classification.EmployeeClassificationName;
                context.SaveChanges();
            }
            else
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        {
            //Get a fresh copy of the row from the database
            var temp = context.EmployeeClassifications.Find(classification.EmployeeClassificationKey);
            if (temp != null)
            {
                //Copy the changed fields
                temp.EmployeeClassificationName = classification.EmployeeClassificationName;
                context.SaveChanges();
                return true;
            }
            else
                return false;
        }
    }
}
</code></pre>

<h2 id="linq-to-db">LINQ to DB<a class="headerlink" href="#linq-to-db" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = new OrmCookbook())
        {
            return db.InsertWithInt32Identity(classification);
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var db = new OrmCookbook())
        {
            var rowCount = db.EmployeeClassification.Where(d =&gt; d.EmployeeClassificationKey == employeeClassificationKey).Delete();
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var db = new OrmCookbook())
        {
            return 1 == db.EmployeeClassification.Where(d =&gt; d.EmployeeClassificationKey == employeeClassificationKey).Delete();
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = new OrmCookbook())
        {
            var rowCount = db.EmployeeClassification.Where(d =&gt; d.EmployeeClassificationKey == classification.EmployeeClassificationKey).Delete();
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = new OrmCookbook())
        {
            return 1 == db.EmployeeClassification.Where(d =&gt; d.EmployeeClassificationKey == classification.EmployeeClassificationKey).Delete();
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        using (var db = new OrmCookbook())
        {
            return db.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).Single();
        }
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        using (var db = new OrmCookbook())
        {
            return db.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName).SingleOrDefault();
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        using (var db = new OrmCookbook())
        {
            return db.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationKey == employeeClassificationKey).Single();
        }
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var db = new OrmCookbook())
        {
            return db.EmployeeClassification.Where(ec =&gt; ec.EmployeeClassificationKey == employeeClassificationKey).SingleOrDefault();
        }
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = new OrmCookbook())
        {
            var rowCount = db.Update(classification);
            if (rowCount != 1)
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = new OrmCookbook())
        {
            return 1 == db.Update(classification);
        }
    }
}
</code></pre>

<h2 id="llblgen-pro">LLBLGen Pro<a class="headerlink" href="#llblgen-pro" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassificationEntity&gt;
{
    public int Create(EmployeeClassificationEntity classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            adapter.SaveEntity(classification, true, recurse: false);
            return classification.EmployeeClassificationKey;
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var adapter = new DataAccessAdapter())
        {
            // delete directly
            int count = adapter.DeleteEntitiesDirectly(typeof(EmployeeClassificationEntity),
                                           new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                       .Equal(employeeClassificationKey)));
            if (count &lt;= 0)
            {
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
            }
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var adapter = new DataAccessAdapter())
        {
            // delete directly
            int count = adapter.DeleteEntitiesDirectly(typeof(EmployeeClassificationEntity),
                                                       new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                                   .Equal(employeeClassificationKey)));
            return count &gt; 0;
        }
    }

    public void DeleteOrException(EmployeeClassificationEntity classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            classification.IsNew = false;
            if (!adapter.DeleteEntity(classification))
            {
                throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
            }
        }
    }

    public bool DeleteWithStatus(EmployeeClassificationEntity classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            classification.IsNew = false;
            return adapter.DeleteEntity(classification);
        }
    }

    public EmployeeClassificationEntity FindByNameOrException(string employeeClassificationName)
    {
        using (var adapter = new DataAccessAdapter())
        {
            return new LinqMetaData(adapter).EmployeeClassification
                                .Single(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName);
        }
    }

    public EmployeeClassificationEntity? FindByNameOrNull(string employeeClassificationName)
    {
        using (var adapter = new DataAccessAdapter())
        {
            return new LinqMetaData(adapter).EmployeeClassification
                                .SingleOrDefault(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName);
        }
    }

    public EmployeeClassificationEntity GetByKeyOrException(int employeeClassificationKey)
    {
        using (var adapter = new DataAccessAdapter())
        {
            var ec = adapter.FetchNewEntity&lt;EmployeeClassificationEntity&gt;(
                                    new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                            .Equal(employeeClassificationKey)));
            if (ec.IsNew)
            {
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
            }
            return ec;
        }
    }

    public EmployeeClassificationEntity? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var adapter = new DataAccessAdapter())
        {
            var ec = adapter.FetchNewEntity&lt;EmployeeClassificationEntity&gt;(
                                    new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                            .Equal(employeeClassificationKey)));
            return ec.IsNew ? null : ec;
        }
    }

    public void UpdateOrException(EmployeeClassificationEntity classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            var toPersist = adapter.FetchNewEntity&lt;EmployeeClassificationEntity&gt;(
                                    new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                            .Equal(classification.EmployeeClassificationKey)));
            if (!toPersist.IsNew)
            {
                toPersist.EmployeeClassificationName = classification.EmployeeClassificationName;
                if (adapter.SaveEntity(toPersist))
                {
                    // succeeded.
                    return;
                }
                // save failed...
            }
            throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassificationEntity classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            var toPersist = adapter.FetchNewEntity&lt;EmployeeClassificationEntity&gt;(
                                    new RelationPredicateBucket(EmployeeClassificationFields.EmployeeClassificationKey
                                                                                            .Equal(classification.EmployeeClassificationKey)));
            if (!toPersist.IsNew)
            {
                toPersist.EmployeeClassificationName = classification.EmployeeClassificationName;
                return adapter.SaveEntity(toPersist, refetchAfterSave: false, recurse: false);
            }
            return false;
        }
    }
}
</code></pre>

<h2 id="nhibernate">NHibernate<a class="headerlink" href="#nhibernate" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>In some cases you'll need to catch a <code>StaleStateException</code> as there is no TryUpdate or TryDelete.</p>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    readonly ISessionFactory m_SessionFactory;

    public TryCrudScenario(ISessionFactory sessionFactory)
    {
        m_SessionFactory = sessionFactory;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        {
            session.Save(classification);
            session.Flush();
            return classification.EmployeeClassificationKey;
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var session = m_SessionFactory.OpenSession())
        {
            session.Delete(new EmployeeClassification() { EmployeeClassificationKey = employeeClassificationKey });
            session.Flush();
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var session = m_SessionFactory.OpenSession())
        {
            var temp = session.Get&lt;EmployeeClassification&gt;(employeeClassificationKey);
            if (temp == null)
                return false;
            session.Delete(temp);
            session.Flush();
            return true;
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        {
            session.Delete(classification);
            session.Flush();
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        {
            try
            {
                session.Delete(classification);
                session.Flush();
                return true;
            }
            catch (StaleStateException ex) when (ex.Message.Contains(&quot;Batch update returned unexpected row count from update;&quot;, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        using (var session = m_SessionFactory.OpenStatelessSession())
        {
            return session.QueryOver&lt;EmployeeClassification&gt;()
                .Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName)
                .List().Single();
        }
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        using (var session = m_SessionFactory.OpenStatelessSession())
        {
            return session.QueryOver&lt;EmployeeClassification&gt;()
                .Where(ec =&gt; ec.EmployeeClassificationName == employeeClassificationName)
                .List().SingleOrDefault();
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        using (var session = m_SessionFactory.OpenStatelessSession())
            return session.Get&lt;EmployeeClassification&gt;(employeeClassificationKey) ?? throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var session = m_SessionFactory.OpenStatelessSession())
            return session.Get&lt;EmployeeClassification&gt;(employeeClassificationKey);
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        {
            session.Update(classification);
            session.Flush();
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        {
            try
            {
                session.Update(classification);
                session.Flush();
                return true;
            }
            catch (StaleStateException ex) when (ex.Message.Contains(&quot;Batch update returned unexpected row count from update;&quot;, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
        }
    }
}
</code></pre>

<h2 id="repodb">RepoDb<a class="headerlink" href="#repodb" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public class TryCrudScenario : BaseRepository&lt;EmployeeClassification, SqlConnection&gt;,
    ITryCrudScenario&lt;EmployeeClassification&gt;
{
    public TryCrudScenario(string connectionString)
        : base(connectionString, RDB.Enumerations.ConnectionPersistency.Instance)
    { }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return Insert&lt;int&gt;(classification);
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        var rowCount = Delete(employeeClassificationKey);
        if (rowCount != 1)
            throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        return 1 == Delete(employeeClassificationKey);
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var rowCount = Delete(classification);
        if (rowCount != 1)
            throw new DataException($&quot;No row was found for key {classification.EmployeeClassificationKey}.&quot;);
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return 1 == Delete(classification);
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        var entity = Query(e =&gt; e.EmployeeClassificationName == employeeClassificationName).FirstOrDefault();
        if (null == entity)
            throw new DataException($&quot;Message&quot;);

        return entity;
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        return Query(e =&gt; e.EmployeeClassificationName == employeeClassificationName).FirstOrDefault();
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        var entity = Query(employeeClassificationKey).FirstOrDefault();
        if (null == entity)
            throw new DataException($&quot;Message&quot;);

        return entity;
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        return Query(employeeClassificationKey).FirstOrDefault();
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        var rowCount = Update(classification);
        if (rowCount != 1)
            throw new DataException($&quot;Message&quot;);
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        return 1 == Update(classification);
    }
}
</code></pre>

<h2 id="servicestack">ServiceStack<a class="headerlink" href="#servicestack" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>Like ADO.NET, this uses the row counts returned from the <code>Execute</code> command.</p>
<pre><code class="cs">public class TryCrudScenario : ITryCrudScenario&lt;EmployeeClassification&gt;
{
    private readonly IDbConnectionFactory _dbConnectionFactory;

    public TryCrudScenario(IDbConnectionFactory dbConnectionFactory)
    {
        _dbConnectionFactory = dbConnectionFactory;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return (int)db.Insert(classification, true);
        }
    }

    public void DeleteByKeyOrException(int employeeClassificationKey)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            var deleted = db.DeleteById&lt;EmployeeClassification&gt;(employeeClassificationKey);
            if (deleted != 1)
                throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        }
    }

    public bool DeleteByKeyWithStatus(int employeeClassificationKey)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return db.DeleteById&lt;EmployeeClassification&gt;(employeeClassificationKey) == 1;
        }
    }

    public void DeleteOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            var deleted = db.DeleteById&lt;EmployeeClassification&gt;(classification.Id);
            if (deleted != 1)
                throw new DataException($&quot;No row was found for key {classification.Id}.&quot;);
        }
    }

    public bool DeleteWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return db.DeleteById&lt;EmployeeClassification&gt;(classification.Id) == 1;
        }
    }

    public EmployeeClassification FindByNameOrException(string employeeClassificationName)
    {
        EmployeeClassification? record = null;
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            record = db.Single&lt;EmployeeClassification&gt;(
                r =&gt; r.EmployeeClassificationName == employeeClassificationName);
        }

        if (record == null)
            throw new DataException($&quot;No row was found with name {employeeClassificationName}.&quot;);
        return record;
    }

    public EmployeeClassification? FindByNameOrNull(string employeeClassificationName)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return db.Single&lt;EmployeeClassification&gt;(
                r =&gt; r.EmployeeClassificationName == employeeClassificationName);
        }
    }

    public EmployeeClassification GetByKeyOrException(int employeeClassificationKey)
    {
        EmployeeClassification? record = null;
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            record = db.SingleById&lt;EmployeeClassification&gt;(employeeClassificationKey);
        }

        if (record == null)
            throw new DataException($&quot;No row was found for key {employeeClassificationKey}.&quot;);
        return record;
    }

    public EmployeeClassification? GetByKeyOrNull(int employeeClassificationKey)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return db.SingleById&lt;EmployeeClassification&gt;(employeeClassificationKey);
        }
    }

    public void UpdateOrException(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            var updated = db.Update(classification);
            if (updated != 1)
                throw new DataException($&quot;No row was found for key {classification.Id}.&quot;);
        }
    }

    public bool UpdateWithStatus(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            return db.Update(classification) == 1;
        }
    }
}
</code></pre>


                    </div>
                </div>
                <footer>
                    <hr />
                    <div role="contentinfo">
The ORM Cookbook. <a href='https://github.com/Grauenwolf/DotNet-ORM-Cookbook' target='_blank'>Visit us at GitHub</a>.
                    </div>
                </footer>
            </div>
        </section>
    </div>
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/modernizr-2.8.3.min.js"></script>
    <script src="js/highlight.pack.js"></script>
    <script src="js/theme.js"></script>

</body>
</html>
